<template>
  <div></div>
</template>
<script>
import axios from "@/api/request/http";
import md5 from "js-md5";
import Cookies from "js-cookie";
export default {
  data() {
    return {};
  },
  props: {
    token: {
      default: "",
      type: String,
    },
  },
  mounted() {
    setTimeout(() => {
      this.getTokens();
    }, 100);
  },
  methods: {
    getTokens() {
      if (Cookies.get("ServiceToken")) {
        this.connectWebsocket();
        console.log("不执行获取token了");
        return;
      }
      let data = {
        userid: "80000002",
        pwd: md5("123456"),
      };
      axios({
        method: "POST",
        url: `http://172.18.26.159:9938/acdproxyapi/GetTokenService/GetToken`,
        data,
      }).then(({ data }) => {
        Cookies.set("ServiceToken", data.data, { expires: 3 });
        this.connectWebsocket();
      });
    },
    connectWebsocket() {
      let websocket;
      let protocol = "ws";
      if (typeof WebSocket === "undefined") {
        console.log("您的浏览器不支持WebSocket");
        return;
      } else {
        let url = "";
        if (window.location.protocol == "https:") {
          protocol = "wss";
        }
        url = `${protocol}://172.18.26.159:7005`;

        // 打开一个websocket
        websocket = new WebSocket(url);
        // 建立连接
        websocket.onopen = () => {
          // 发送数据
          let jsonData = {
            msgID: "12345", //消息ID，当前传送指令唯一ID
            cmd: "ReqGetData", //指令名称
            userid: "80000002", //用户ID，发送指令请求的用户ID
            data: { RoleID: 0 }, //传输数据参数或为空，
            token: Cookies.get("ServiceToken"), // Token验证权限和时效
            Version: 1, //版本号
          };
          websocket.send(JSON.stringify(jsonData));
          console.log("websocket发送数据中");
        };
        // 客户端接收服务端返回的数据
        websocket.onmessage = (evt) => {
          this.$emit("getSocketData", JSON.parse(evt.data));
        };
        // 发生错误时
        websocket.onerror = (evt) => {
          console.log("websocket错误：", evt);
        };
        // 关闭连接
        websocket.onclose = (evt) => {
          console.log("websocket关闭：", evt);
        };
      }
    },
  },
};
</script>
<style scoped></style>
